package com.lse_from.utils

import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import freemarker.template.Configuration
import freemarker.template.Template
import java.io.BufferedWriter
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.util.*
import kotlin.jvm.Throws

/**
 * 公共通用工具
 *
 * @author 祁雪
 */
class PubUtil {

    companion object {

        fun getUUID(): String {
            return UUID.randomUUID().toString()
        }

        @Throws(Exception::class)
        fun toJson(any: Any): String {
            val mapper = ObjectMapper()
            return mapper.writeValueAsString(any)
        }

        @Throws(Exception::class)
        fun toGJson(any: Any, timeStr: String?): String {
            val gsonBuilder = GsonBuilder()
            if (timeStr != null && timeStr.isNotBlank()) {
                gsonBuilder.setDateFormat(timeStr)
            }
            return gsonBuilder.create().toJson(any)
        }

        fun getGson(): Gson {
            return GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
        }

        fun checkJson(jsonStr: String): Boolean {
            val gson = getGson()
            try {
                gson.fromJson(jsonStr, object : TypeToken<Any>() {}.type) as Any
                return true
            } catch (e: Exception) {
                return false
            }
        }

        /**
         * 根据ftl模板生成文件
         */
        fun createFileByFtl(
            path: String,
            fileName: String,
            templatePath: String,
            templateName: String,
            data: Any
        ) {
            println("开始执行文件生成")

            val config = Configuration(Configuration.getVersion())
            config.setDirectoryForTemplateLoading(File(templatePath))
            val template = config.getTemplate(templateName)
            val file = File(path, fileName)

            val outFile = BufferedWriter(OutputStreamWriter(FileOutputStream(file)))

            outFile.use {
                template.process(data, it)
            }

            println("文件生成完毕 => ${file.absolutePath}")
        }

    }

}